# -*- coding : utf_8 -*-
'''
=======================================
Time : 2025/3/24 20:22
Author : 田霄汉
Email : 522989570@qq.com
File : dingrobot_util.py
Project : pytest_demo
=======================================
'''
import base64
import hashlib
import hmac
import time
from urllib import parse
import requests
from config import setting


class DingrobotUtil:

    @classmethod
    def generate_sign(cls):
        """
        生成签名
        :return: 返回时间戳和加签
        """
        # 获取时间戳
        timestamp = str(round(time.time()*1000))
        # 获取钉钉机器人里面的加签秘钥
        # secret = 'SEC1b644b5d4c9675e62ae8bf2ae31a8cda994ea3f3745b1dd16a3e4babe10150d1'
        secret = setting.secret
        # 对加签秘钥进行转码
        secret_encode = secret.encode(encoding='utf-8')
        # 组合当前时间戳和加签秘钥
        time_join_secrt = f'{timestamp}\n{secret}'
        # 再次转码，转成byte类型
        time_join_secrt_encode = time_join_secrt.encode(encoding='utf-8')
        # 进行加密
        hash_secret = hmac.new(key=secret_encode, msg=time_join_secrt_encode, digestmod=hashlib.sha256).digest()
        # 生成加签sign
        sign = parse.quote_plus(base64.b64encode(hash_secret))

        # 返回时间戳和sign
        return timestamp, sign

    @classmethod
    def send_dd_msg(cls, content, at_all):
        """
        向钉钉群发送消息
        :param content: 发送的文本
        :param at_all: 是否@全部人，默认为True
        :return:
        """
        timestamp, sign = cls.generate_sign()
        # 拼接组成url
        url = f'{setting.webhook}&timestamp={timestamp}&sign={sign}'
        headers = {
            'Content-Type': 'application/json;charset=UTF-8'
        }
        data = {
            'msgtype': 'text',
            'text': {
                'content': content
            },
            'at': {
                'isAtAll': at_all
            }
        }
        res = requests.post(url=url, json=data, headers=headers)
        return res.text
